package com.maomao.ssoserver.config.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.maomao.ssoserver.model.BaseResources;
import com.maomao.ssoserver.model.BaseRole;
import com.maomao.ssoserver.model.BaseUser;
import com.maomao.ssoserver.service.ResourcesService;
import com.maomao.ssoserver.service.RoleService;
import com.maomao.ssoserver.service.UserService;


public class MyShiroRealm extends AuthorizingRealm {

	@Autowired
    private UserService userService;

    @Autowired
    private ResourcesService resourcesService;
    
    @Autowired
    private RoleService roleService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        BaseUser user= (BaseUser) SecurityUtils.getSubject().getPrincipal();
        List<BaseRole> roles = roleService.findByUserId(user.getId());
        List<BaseResources> resourcesList = resourcesService.findByUserId(user.getId());
        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for(BaseRole role : roles){
        	info.addRole(role.getRoleName());
        }
        for(BaseResources resources: resourcesList){
            info.addStringPermission(resources.getName());
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
    	
        String username = (String)token.getPrincipal();
       
        BaseUser user = userService.findbyUsername(username);
        if(user==null) throw new UnknownAccountException();
        if (0==user.getIsValid()) {
            throw new LockedAccountException(); // 帐号锁定
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUserName(), //用户
                user.getPassword(), //密码
                ByteSource.Util.bytes("admin"+user.getSalt()),
                getName()  //realm name
        );
        
        return authenticationInfo;
    }
}
